/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package validators;

import facades.UserFacade;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

/**
 *
 * @author damfercer
 */
@Named
@RequestScoped
public class LoginEmailValidator implements Validator{
    @EJB
    private UserFacade userEJB;
    private static final String emailPattern="^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$";
    private Pattern pattern;
    private Matcher matcher;
    
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        Locale locale=context.getViewRoot().getLocale();
        ResourceBundle rb = ResourceBundle.getBundle("messages", locale);
        pattern = Pattern.compile(emailPattern);
        matcher = pattern.matcher(value.toString().toLowerCase());
        String email=value.toString().toLowerCase();
        if(!matcher.matches()){
            String patternErrorMsg=rb.getString("EmailPattern");
            FacesMessage msg =new FacesMessage(patternErrorMsg, patternErrorMsg);
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
	}
        /*else if(!userEJB.isEmailRegistered(email)){
            String emailInUseMsn=rb.getString("EmailNotUsed");
            FacesMessage msg =new FacesMessage(emailInUseMsn,emailInUseMsn);
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }*/
        
    }
    
}
